package controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import util.DBUtil;

@WebServlet("/deleteMember")
public class DeleteMemberServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 设置请求和响应的字符编码为 UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=UTF-8");

        PrintWriter out = response.getWriter();

        String memberId = request.getParameter("id");

        if (memberId == null || memberId.isEmpty()) {
            String jsonResponse = "{\"message\": \"成员ID不能为空\"}";
            out.print(jsonResponse);
            return;
        }

        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = DBUtil.getConnection();
            String deleteSQL = "DELETE FROM users WHERE id = ?";
            preparedStatement = connection.prepareStatement(deleteSQL);
            preparedStatement.setInt(1, Integer.parseInt(memberId));

            int rowsAffected = preparedStatement.executeUpdate();
            String jsonResponse;
            if (rowsAffected > 0) {
                jsonResponse = "{\"message\": \"成员删除成功\"}";
            } else {
                jsonResponse = "{\"message\": \"成员删除失败，可能不存在该成员\"}";
            }
            out.print(jsonResponse);
        } catch (SQLException e) {
            String jsonResponse = "{\"message\": \"删除成员时发生错误\"}";
            out.print(jsonResponse);
            e.printStackTrace();
        } finally {
            DBUtil.close(connection, preparedStatement, null);
        }
    }
}
